import time

import jwt
from rest_framework.response import Response

from oasystem2 import settings


def check_userjwt(request):
    token = request.headers.get("Token")
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms="HS256")
    except Exception as e:
        print("校验token报错: %s" % e)
        payload = None
    return payload


# 检测用户登录的装饰器
def check_user(func):
    def check(cls,request):
        token = request.META.get('HTTP_TOKEN')
        try:
            payload = jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
            if payload['time'] < int(time.time()):
                return Response({'code':400,'msg':'token失败'})
        except Exception as e:
            return Response({'code':400,'msg':'验证失败'})
        return func(cls,request,payload)
    return check

